package arch.chameleon.module.security.realm.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义身份验证过滤器
 * （同时支持异步和同步的未通过身份验证的返回与跳转）
 * @author George
 *
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

	private transient Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		 	if (isLoginRequest(request, response)) {
	            if (isLoginSubmission(request, response)) {
	                if (log.isTraceEnabled()) {
	                    log.trace("Login submission detected.  Attempting to execute login.");
	                }
	                return executeLogin(request, response);
	            } else {
	                if (log.isTraceEnabled()) {
	                    log.trace("Login page view.");
	                }
	                //allow them to see the login page ;)
	                return true;
	            }
	        } else {
	            saveRequestAndRedirectToLogin(request, response);
	            return false;
	        }
		
		
		
	}
	
	@Override
	protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
		HttpServletRequest objHttpServletRequest = (HttpServletRequest)request;
		String strRequestURI = objHttpServletRequest.getRequestURI();
		log.debug("REQUEST URI: {}", new Object[]{strRequestURI});
		saveRequest(request);
		if(StringUtils.isNotBlank(strRequestURI) && strRequestURI.endsWith(".".concat(asynRequestSuffix))){	
			log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                    "Authentication url [{}]", new Object[]{asyncLoginUrl});
			Map<String, String> mpParams = new HashMap<String, String>();
			mpParams.put("REQ_MESSAGE", "{\"REQ_HEAD\":{\"OPERATE\":\"\"},\"REQ_BODY\":{}}");
			WebUtils.issueRedirect(request, response, asyncLoginUrl, mpParams, true, true);
		}else{
			log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                    "Authentication url [{}]", new Object[]{syncLoginUrl});
			WebUtils.issueRedirect(request, response, syncLoginUrl);
		}
    }
	
	
	

	
	/**
	 * 同步跳转URL
	 */
	private String syncLoginUrl;
	
	/**
	 * 异步返回URL
	 */
	private String asyncLoginUrl;
	
	/**
	 * 异步请求后缀(如json, ajax等)
	 */
	private String asynRequestSuffix;


	public void setSyncLoginUrl(String syncLoginUrl) {
		this.syncLoginUrl = syncLoginUrl;
	}

	public void setAsyncLoginUrl(String asyncLoginUrl) {
		this.asyncLoginUrl = asyncLoginUrl;
	}

	public void setAsynRequestSuffix(String asynRequestSuffix) {
		this.asynRequestSuffix = asynRequestSuffix;
	}
	
	
	
	
}
